#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PID_FILE="${ROOT_DIR}/uvicorn.pid"
RSSHUB_DIR="${ROOT_DIR}/rsshub"
RSSHUB_PID_FILE="${ROOT_DIR}/rsshub.pid"
RSSHUB_MODE="${RSSHUB_MODE:-docker}"

command_exists() {
    command -v "$1" >/dev/null 2>&1
}

docker_compose() {
    if docker compose version >/dev/null 2>&1; then
        docker compose "$@"
    elif command_exists docker-compose; then
        docker-compose "$@"
    else
        echo "❌ 未检测到 docker compose，请安装 Docker Compose v2 或 docker-compose"
        exit 1
    fi
}

stop_api() {
    if [[ ! -f "${PID_FILE}" ]]; then
        echo "[api] 未找到 PID 文件，可能未启动"
        return
    fi

    pid="$(cat "${PID_FILE}")"
    if ! kill -0 "${pid}" >/dev/null 2>&1; then
        echo "[api] PID ${pid} 不存在，清理残留 PID 文件"
        rm -f "${PID_FILE}"
        return
    fi

    echo "[api] 停止 FastAPI (pid ${pid}) ..."
    kill "${pid}" || true
    for _ in {1..10}; do
        if kill -0 "${pid}" >/dev/null 2>&1; then
            sleep 1
        else
            break
        fi
    done

    if kill -0 "${pid}" >/dev/null 2>&1; then
        echo "[api] 进程未退出，发送 SIGKILL"
        kill -9 "${pid}" || true
    fi

    rm -f "${PID_FILE}"
    echo "[api] 已停止"
}

stop_rsshub() {
    if [[ "${RSSHUB_MODE}" == "docker" ]]; then
        if ! command_exists docker; then
            echo "[rsshub] ⚠️ 未检测到 docker (docker 模式)，跳过"
            return
        fi
        echo "[rsshub] (docker) 停止 RSSHub 及依赖 ..."
        (cd "${ROOT_DIR}" && docker_compose stop rsshub browserless redis)
        return
    fi

    if [[ ! -f "${RSSHUB_PID_FILE}" ]]; then
        echo "[rsshub] (node) 未找到 PID 文件，可能未启动"
        return
    fi
    pid="$(cat "${RSSHUB_PID_FILE}")"
    if ! kill -0 "${pid}" >/dev/null 2>&1; then
        echo "[rsshub] (node) PID ${pid} 不存在，清理残留 PID 文件"
        rm -f "${RSSHUB_PID_FILE}"
        return
    fi
    echo "[rsshub] (node) 停止 RSSHub (pid ${pid}) ..."
    kill "${pid}" || true
    for _ in {1..10}; do
        if kill -0 "${pid}" >/dev/null 2>&1; then
            sleep 1
        else
            break
        fi
    done
    if kill -0 "${pid}" >/dev/null 2>&1; then
        echo "[rsshub] (node) 进程未退出，发送 SIGKILL"
        kill -9 "${pid}" || true
    fi
    rm -f "${RSSHUB_PID_FILE}"
    echo "[rsshub] (node) 已停止"
    if command_exists docker; then
        echo "[rsshub] (node) 停止 redis / browserless 容器 ..."
        (cd "${ROOT_DIR}" && docker_compose stop redis browserless)
    fi
}

stop_postgres() {
    if ! command_exists docker; then
        return
    fi
    echo "[postgres] 停止 docker compose postgres ..."
    (cd "${ROOT_DIR}" && docker_compose stop postgres)
}

main() {
    stop_api
    stop_rsshub
    stop_postgres
    echo "✅ 已完成停止操作"
}

main "$@"
